from flask import Flask
from config import config_map
import redis
from flask_sqlalchemy import SQLAlchemy

# 导入设置日志级别的函数
from ihome.utils.common import set_log_level,ReConverter
import logging
# set_log_level(logging.DEBUG) # 设置日志级别
# set_log_level(logging.INFO) # 设置日志级别
# set_log_level(logging.WARNING) # 设置日志级别
set_log_level(logging.ERROR) # 设置日志级别

# 实例化SQLALCHEMY对象
db = SQLAlchemy()
redis_store=None
# 将创建app的工作封装成函数
def create_app(config_name):
    app = Flask(__name__)
    config_class = config_map.get(config_name)
    app.config.from_object(config_class)

    # 初始化app
    db.init_app(app)
    # 创建连接Redis数据库的对象
    global redis_store
    redis_store = redis.StrictRedis(host=config_class.REDIS_HOST,port=config_class.REDIS_PORT)
    # 实例化Flask-Session模块中的Session对象，将app传递进去就可以自定义Session信息的存储位置了
    from flask_session import Session
    Session(app)

    # 为flask补充csrf防护
    from flask_wtf import CSRFProtect
    # 解决跨站伪造攻击防护
    # 原理：cookie_csrf_token=request.cookies.get("csrf_token")
    # form_csrf_token=request.form.get("csrf_token")
    # cookie_csrf_token==form_csrf_token
    # header_csrf_token=request.headers["X-CSRFToken"]
    # return cookie_csrf_token==header_csrf_token
    # CSRFProtect(app)


    # 2. 注册转换器
    app.url_map.converters["re"] = ReConverter
    print("查看系统内置的转换器：",app.url_map.converters)
    # 4. 注册蓝图
    from ihome.web_html import html
    from ihome import api_1_0
    from ihome import api_2_0
    app.register_blueprint(html) # 注册访问静态资源的蓝图
    app.register_blueprint(api_1_0.api,url_prefix="/api/v1.0")
    app.register_blueprint(api_2_0.api,url_prefix="/api/v2.0")
    return app
